package com.homedo.odin.solution.controller.pc;

import com.homedo.core.common.base.controller.BaseController;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.base.dto.ResultData;
import com.homedo.core.common.exception.BizException;
import com.homedo.odin.solution.enumcode.require.UserRequireStatusEnum;
import com.homedo.odin.solution.model.entity.UserRequire;
import com.homedo.odin.solution.model.request.pc.require.UserRequireListRequestBean;
import com.homedo.odin.solution.model.request.pc.require.UserRequirePcRequestBean;
import com.homedo.odin.solution.service.bizservice.mng.MngUserRequireService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Api(description = "用户定制需求", tags = {"Requirement"},
        produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/reqs")
public class UserRequireController extends BaseController<MngUserRequireService> {

    @PostMapping
    @ApiOperation(value = "PC_用户提交需求", httpMethod = "POST")
    public ResultData addUserRequire(@Valid @RequestBody UserRequirePcRequestBean requestBean,
            BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultData.newInstance(new Meta(Meta.CODE_451.getCode(),
                    bindingResult.getFieldError().getDefaultMessage()));
        }
        baseService.addUserRequire(requestBean);
        return ResultData.newInstance("用户提交需求成功!");
    }

    @GetMapping()
    @ApiOperation(value = "PC_我的需求", response = UserRequire.class, httpMethod = "GET")
    public ResultData getUserRequires(@Valid @ModelAttribute UserRequireListRequestBean requestBean,
            BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultData.newInstance(new Meta(Meta.CODE_451.getCode(),
                    bindingResult.getFieldError().getDefaultMessage()));
        }
        if (null != requestBean.getStatus() && UserRequireStatusEnum.getName(requestBean.getStatus()) == null) {
            throw new BizException(new Meta(Meta.CODE_451.getCode(), "回复状态有误"));
        }
        if (requestBean.getStartCreateDate() != null && requestBean.getEndCreateDate() != null
                && requestBean.getStartCreateDate() > requestBean.getEndCreateDate()) {
            return ResultData.newInstance(new Meta(Meta.CODE_451.getCode(), "时间区间不合法"));
        }
        return ResultData.newInstance(Meta.CODE_200, baseService.getUserRequiresByUser(requestBean));
    }
}
